/**
 * Xinfei.com Inc.
 * Copyright (c) 2004-2023 All Rights Reserved.
 */
package com.xinfei.techplayprod.biz;

import com.xinfei.techplayprod.bootstrap.Application;
import com.xinfei.xfframework.common.JsonUtil;
import com.xinfei.xfframework.common.starter.feign.XFFeignClient;
import com.xinfei.xfframework.context.Context;
import feign.Request;
import feign.Response;
import feign.Util;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * 单系统集成测试基类
 *
 * @author Jinyan.Huang
 * @version $ TechplayDevTestBase, v 0.1 2023/8/29 21:28 Jinyan.Huang Exp $
 */
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"local", "test"})
@AutoConfigureMockMvc
public abstract class TechplayDevTestBase {

    @Autowired
    XFFeignClient xfFeignClient;

    public <T> T post(String path, Object request, Class<T> t) throws IOException {
        Map<String, Collection<String>> headers = new HashMap<>();
        headers.put("Content-Type", Arrays.asList("application/json"));
        byte[] bytes = null;
        if (request != null) {
            bytes = JsonUtil.toJsonNull(request).getBytes(UTF_8);
        }
        Request request1 = Request.create(Request.HttpMethod.POST, "http://" + Context.APP_NAME + "/" + path, headers, bytes, UTF_8);
        Response response = xfFeignClient.execute(request1, new Request.Options());
        try {
            final byte[] bodyData = Util.toByteArray(response.body().asInputStream());
            return JsonUtil.parseJson(new String(bodyData), t);
        } finally {
            response.close();
        }
    }

    public <T> T get(String path, Class<T> t) throws IOException {
        Map<String, Collection<String>> headers = new HashMap<>();
        headers.put("Content-Type", Arrays.asList("application/json"));
        Request request1 = Request.create(Request.HttpMethod.GET, "http://" + Context.APP_NAME + "/" + path, headers, (Request.Body) null, null);
        Response response = xfFeignClient.execute(request1, new Request.Options());
        try {
            final byte[] bodyData = Util.toByteArray(response.body().asInputStream());
            return JsonUtil.parseJson(new String(bodyData), t);
        } finally {
            response.close();
        }
    }
}
